package org.boulderfoodrescue.webapp.client.pickuptimes;

import org.boulderfoodrescue.webapp.client.managers.TimeSlotManager;
import org.boulderfoodrescue.webapp.client.pickuptimes.timepicker.DateTimePicker;
import org.boulderfoodrescue.webapp.client.pickuptimes.timepicker.PickupWindow;
import org.boulderfoodrescue.webapp.client.pickuptimes.timepicker.PickupWindow.RepeatType;
import org.boulderfoodrescue.webapp.shared.Location;
import org.boulderfoodrescue.webapp.shared.OneTimeEvent;
import org.boulderfoodrescue.webapp.shared.RecurringEvent;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Widget;

public class TimeSlotsContentView extends Composite{

	private static ConfirmDialogViewUiBinder uiBinder = GWT
			.create(ConfirmDialogViewUiBinder.class);

	interface ConfirmDialogViewUiBinder extends
	UiBinder<Widget, TimeSlotsContentView> {
	}

	public TimeSlotsContentView(TimeSlotInterface timeSlotInterface, Location location) {
		initWidget(uiBinder.createAndBindUi(this));
		this.timeSlotInterface = timeSlotInterface;
		this.location = location;
	}

	@UiField
	Button addButton;
	@UiField
	Button backButton;
	@UiField
	DateTimePicker dateTimePicker;
	@UiField
	TimeSlotsTableWeekly weeklyTable;
	@UiField
	TimeSlotsTableOneTime oneTimeTable;

	private Location location;
	private TimeSlotInterface timeSlotInterface;

	@UiHandler("addButton")
	public void onOkButtonClick(ClickEvent event)
	{
		PickupWindow pw = dateTimePicker.getPickupWindow();
		if(pw.getRepeatType() == RepeatType.None){
			OneTimeEvent singleTime = new OneTimeEvent();
			singleTime.setStartTime(pw.getStart_time());
			singleTime.setEndTime(pw.getEnd_time());
			singleTime.setLocationKey(location.getDatabaseKey());
			TimeSlotManager.SaveOneTimeEvent(singleTime);
		}
		else{
			RecurringEvent re = new RecurringEvent(pw);
			re.setLocationKey(location.getDatabaseKey());
			TimeSlotManager.SaveRecurringEvent(re);
		}
	}

	@UiHandler("backButton")
	public void onBackButtonClick(ClickEvent event)
	{
		timeSlotInterface.onBackClicked();
	}

	public void addOneTimeEvent(OneTimeEvent event){
		oneTimeTable.addOneTimeEvent(event);
	}

	public void addRecurringEvent(RecurringEvent event){
		switch(event.getRepeatType()){
		case Weekly: 
			weeklyTable.addRecurringEvent(event);
			break;
		}
	}
}
